
#include <iostream>
#include <string>
using namespace std;

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include <unistd.h>
#include <stdio.h>
#include <cstring>

void Usage()
{
    cout << "Usage: ip port" << endl;
}

int main(int argc,char* argv[])
{   
    if(argc != 3)
    {
        Usage();
        return 1;
    }

    string ip = argv[1];
    int16_t port = atoi(argv[2]);

    int fd = socket(AF_INET,SOCK_STREAM,0);
    if(fd < 0)
    {
        cerr << "socket fail" << endl;
        return 1;
    }

    struct sockaddr_in addr;
    socklen_t len = sizeof(addr);
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = INADDR_ANY;
    addr.sin_port = htons(port);
    
    int n = bind(fd,(struct sockaddr*)&addr,len);
    if(n < 0)
    {
        cerr << "bind fail" << endl;
        return 2;
    }

    n = listen(fd,4);
    if(n < 0)
    {
        cerr << "listen fail" << endl;
        return 3;
    }

    while(true)
    {
        struct sockaddr_in client_addr;
        socklen_t len;
        int client_fd = accept(fd,(struct sockaddr*)&client_addr,&len);
        if(client_fd < 0)
        {
            continue;
        }

        char req[1024 * 4] = { 0 };
        int size = read(client_fd,&req,sizeof(req) - 1);
        if(size > 0)
        {
            req[size] = '\0';
            printf("请求：------\n %s",req);
        }

        char resp[1024] = { 0 };
        const char* body = "<h1>hello world</h1>";
        sprintf(resp,"HTTP/1.0 200 OK\nContent-Length:%lu\n\n%s",strlen(body),body);
        write(client_fd,&resp,strlen(resp));
    }
    return 0;
}